package goutils

import (
	"bufio"
	"io/ioutil"
	"os"
)

// 读取所有文件
func ReadFile(filename string) ([]byte, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return ioutil.ReadAll(f)
}

// 读取文件到字符串，失败返回空字符串
func ReadFile2str(filename string) string {
	f, err := ReadFile(filename)
	if err != nil {
		return ""
	}
	return string(f)
}

// 写文件
func WriteFile4str(filename string, data string) error {
	bdata := []byte(data)
	return WriteFile4byte(filename, &bdata)
}
func WriteFile4byte(filename string, data *[]byte) error {
	f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	defer f.Close()

	writer := bufio.NewWriterSize(f, 4096)
	if _, err := writer.Write(*data); err == nil {
		if err := writer.Flush(); err != nil {
			return err
		}
	} else {
		return err
	}
	return nil
}

// 写文件，追加
func WriteFile4byteAppend(filename string, data *[]byte) error {
	f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		return err
	}
	defer f.Close()

	writer := bufio.NewWriterSize(f, 4096)
	if _, err := writer.Write(*data); err == nil {
		if err := writer.Flush(); err != nil {
			return err
		}
	} else {
		return err
	}
	return nil
}

//获取指定目录下的所有文件和目录
func ListDir(dirPth string) (files []string, files1 []string, err error) {
	//fmt.Println(dirPth)
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return nil, nil, err
	}
	PthSep := string(os.PathSeparator)
	//    suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

	for _, fi := range dir {

		if fi.IsDir() { // 忽略目录
			files1 = append(files1, dirPth+PthSep+fi.Name())
			ListDir(dirPth + PthSep + fi.Name())
		} else {
			//fmt.Println("s")
			files = append(files, dirPth+PthSep+fi.Name())
		}
	}
	return files, files1, nil
}
